import { setToken } from '@/utils/token';
import { useModel } from '@umijs/max';
import { useMutation, useQuery, useQueryClient } from '@umijs/max';
import { message, notification } from 'antd';
import { request } from '../axios';
import QUERY_KEYS from '../constant';
import APP_PRE from '../constant/app-pre';

const prefix = `${APP_PRE.APP_NAME}/account`;

const useLoginByPassword = (
  callBack?: () => void,
  isNotify: boolean = true,
) => {
  const { setInitialState } = useModel('@@initialState');
  return useMutation(
    (passwordForm: API.IPassword) =>
      request<API.IResult<API.ILoginByPassword>>(
        `/${prefix}/${QUERY_KEYS.PUBLIC}/login`,
        {
          method: 'POST',
          params: {
            email: passwordForm.email,
            password: passwordForm.password,
          },
        },
      ),
    {
      onSuccess: (res: API.IResult<API.ILoginByPassword>) => {
        if (res.code === 200) {
          if (isNotify) notification.success({ message: '登录成功' });
          setToken(res.data.token);
          setInitialState(res.data.account);
          if (callBack) callBack();
        } else {
          message.error('请检查账号和密码');
        }
      },
    },
  );
};

const useRegister = (email: string, password: string) => {
  return useQuery(
    [QUERY_KEYS.ACCOUNT_REGISTER, email, password],
    () =>
      request<API.IResult<API.ILoginByPassword>>(
        `/${prefix}/${QUERY_KEYS.PUBLIC}/register`,
        {
          method: 'POST',
          data: {
            email,
            password,
            // 默认头像
            avatar:
              'https://img0.baidu.com/it/u=3530732730,4271362942&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500',
          },
        },
      ),
    { enabled: false },
  );
};

const useUpdateAccount = () => {
  const query = useQueryClient();
  return useMutation(
    (account: API.IUserInfo) =>
      request<API.IResult<API.IInsertId>>(`${prefix}/update`, {
        method: 'POST',
        data: account,
      }),
    {
      onSuccess: (res: API.IResult<API.IInsertId>) => {
        if (res.code === 200) {
          notification.success({ message: '修改成功' });
          query.invalidateQueries([QUERY_KEYS.ACCOUNT_GET_BY_TOKEN]);
        }
      },
    },
  );
};

const useGetAccount = () => {
  return useQuery([QUERY_KEYS.ACCOUNT_GET_BY_TOKEN], () =>
    request<API.IResult<API.IUserInfo>>(`/${prefix}/getAccount`, {
      method: 'GET',
    }),
  );
};

const getAccount = async () => {
  return await request<API.IResult<API.IUserInfo>>(`/${prefix}/getAccount`, {
    method: 'GET',
  });
};

export {
  useLoginByPassword,
  useGetAccount,
  useRegister,
  getAccount,
  useUpdateAccount,
};
